from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.db import connection, transaction
from .models import t_interface_params, t_interface, t_group,t_total, t_user, t_address
from .tools.w_interface_test import interfaace_test

import json
# Create your views here.

interfaace_con = interfaace_test()

def autoindex(request):
    return render(request, '')

@csrf_exempt
def autologin(request):
    if request.method == "POST":
        print(request.user)
        print(eval(request.body))
        user = {"id": 1, "username": "admin", "avatar": "/static/user.jpg", "name": "王"}
        return HttpResponse(json.dumps({ "code": 200, "msg": '请求成功', "user": user}))

@csrf_exempt
def itf_otherdata(request):
    if request.method == "POST":
        group_data = t_group.objects.filter(is_delete=0).values_list('group_name')
        group_list = []
        for i in group_data:
            group_list.append(i[0])

        return HttpResponse(json.dumps({"group_list":group_list}))

@csrf_exempt
def itf_list(request):
    if request.method == "POST":
        c_name = eval(request.body)
        itf_list = itf_list_sel(c_name["classification_name"])
        gid = int(t_group.objects.get(group_name=c_name["classification_name"]).id)
        address_sel_value, address_sel = other_address_sel(gid)
        user_sel_value, user_sel = other_user_sel(gid)
        return HttpResponse(json.dumps({"itf_list":itf_list,"address_sel_value":address_sel_value,"address_sel":address_sel,"user_sel_value":user_sel_value,"user_sel":user_sel}))

int_fun = interfaace_test()
@csrf_exempt
def itf_returndata(request):
    if request.method == "POST":
        r_data = eval(request.body)
        all_url = ""
        request_data = ""
        _status = 1
        try:
            url = t_interface.objects.filter(id=r_data["lid"]).values_list('url')[0][0]
            all_url = 'http://106.14.39.56:80/group' + url
            request_data = interfaace_con.other_int(all_url, r_data["params"])
            _status = 0
        except BaseException as b:
            _log_err = "itf_returndata函数报错 --》" + str(b)
            print(_log_err)
        finally:
            return HttpResponse(json.dumps({"status":_status,"url":all_url, "request_data":request_data}))

def itf_list_sel(c_name):
    r_data_list = []
    try:
        g_id = t_group.objects.filter(group_name=c_name).values_list("id")[0][0]
        c_list = t_total.objects.filter(g_id=g_id,is_delete=0).values_list("id","itf_name", "itf_de")
        r_data_list = []
        cursor = connection.cursor()
        print(c_list)
        for item in c_list:
            sel_list_sql = """SELECT ti.url, ti.id, ti.method, ti.urlde, ti.request_format, ti.user_load,tip.param_name , tip.describe, tip.data_type, tip.mandatory FROM t_interface ti LEFT JOIN t_interface_params tip ON ti.id = tip.i_id WHERE ti.is_delete=0 AND tip.is_delete=0 AND ti.c_id = {} ORDER BY url""".format(item[0])
            cursor.execute(sel_list_sql)
            sel_itf_data = cursor.fetchall()
            sel_itf_name = [desc[0] for desc in cursor.description]

            objDictO={}
            b_list = ['url','id','method','urlde','request_format','user_load']
            u_list = []
            r_u_list = []
            for row in sel_itf_data:
                url_json={}
                if objDictO=={}:
                    pass
                elif objDictO["url"] != row[0]:
                    objDictO["tableData"] = u_list
                    r_u_list.append(objDictO)
                    u_list = []
                    objDictO = {}
                else:
                    pass
                for index, value in enumerate(row):
                    if sel_itf_name[index] in b_list:
                        objDictO[sel_itf_name[index]] = value
                    else:
                        if sel_itf_name[index] == "mandatory":
                            if value==0:
                                url_json["mandatory"] = False
                            else:
                                url_json["mandatory"] = True
                        else:
                            url_json[sel_itf_name[index]] = value
                url_json["param_val"]=""
                objDictO["buttonshow"] = False
                objDictO["isShow"] = False
                objDictO["url_value"] = ""
                objDictO["return_value"] = ""
                u_list.append(url_json)
            if u_list != []:
                objDictO["tableData"] = u_list
                r_u_list.append(objDictO)
            r_name = item[1] + "：" + item[2]
            r_data_json = {"id":item[0],"name": r_name, "url_list": r_u_list}
            r_data_list.append(r_data_json)
        cursor.close()
    except BaseException as b:
        _log_err = "itf_list_sel函数报错 --》" + str(b)
        r_data_list = []
        print(_log_err)
    finally:
        return r_data_list


@csrf_exempt
def itf_delitf(request):
    if request.method == "POST":
        _status=1
        itf_list = []
        try:
            data = eval(request.body)
            if data["type"] == 0:
                t_total.objects.filter(id=data["itf_id"]).update(is_delete=1)
                t_interface.objects.filter(c_id=data["itf_id"]).update(is_delete=1)
                itf_list = itf_list_sel(data["name"])
            elif data["type"] == 1:
                t_interface.objects.filter(id=data["itf_id"],url=data["itf_name"]).update(is_delete=1)
                itf_list = itf_list_sel(data["name"])
            _status = 0
        except BaseException as b:
            _log_err="itf_delitf函数报错 --》" + str(b)
            print(_log_err)
        finally:
            return HttpResponse(json.dumps({"status":_status,"itf_list": itf_list}))

@csrf_exempt
def itf_moditf(request):
    if request.method == "POST":
        _status = 1
        itf_list = []
        try:
            data = eval(request.body)
            name_list = data["new_name"].split('：')
            print(name_list)
            t_total.objects.filter(id=data["id"]).update(itf_name=name_list[0], itf_de=name_list[1])
            itf_list = itf_list_sel(data["name"])
            _status = 0
        except BaseException as b:
            _log_err = "itf_moditf函数报错 --》" + str(b)
            print(_log_err)
        finally:
            return HttpResponse(json.dumps({"status":_status,"itf_list": itf_list}))

def interface_sel(iid):
    url_json = {}
    url_list = ["method", "url", "urlde", "request_format", "user_load"]
    url_data = t_interface.objects.filter(id=iid).values_list("method", "url", "urlde", "request_format", "user_load")[0]
    for i in range(len(url_list)):
        if url_list[i] == "user_load":
            if int(url_data[i]) == 0:
                url_json[url_list[i]] = False
            else:
                url_json[url_list[i]] = True
        else:
            url_json[url_list[i]] = url_data[i]
    url_json["params_list"] = []

    url_table = []
    url_param_list = ["param_name", "describe", "data_type", "mandatory"]
    url_param_data = t_interface_params.objects.filter(i_id=iid, is_delete=0).values_list("param_name", "describe",
                                                                                    "data_type", "mandatory")
    for a in url_param_data:
        url_param_json = {}
        for b in range(len(url_param_list)):
            if url_param_list[b] == "mandatory":
                if int(a[b]) == 0:
                    url_param_json[url_param_list[b]] = False
                else:
                    url_param_json[url_param_list[b]] = True
            else:
                url_param_json[url_param_list[b]] = a[b]
        url_table.append(url_param_json)
    return  url_json,url_table

@csrf_exempt
def itf_modvalue(request):
    if request.method == "POST":
        r_data = {"status":1}
        try:
            data = eval(request.body)
            url_json, url_table = interface_sel(data["id"])
            print(url_json)
            print(url_table)
            r_data["urlform"] = url_json
            r_data["url_table"] = url_table
            r_data["id"] = data["id"]
            r_data["status"] = 0
        except BaseException as b:
            _log_err = "itf_modvalue函数异常 --》" + str(b)
            print(_log_err)
        finally:
            return HttpResponse(json.dumps(r_data))

#接口操作
@csrf_exempt
def itf_otheradd(request):
    if request.method == "POST":
        false = 0
        true = 1
        data = eval(request.body)
        print(request.body)
        return_json = {"status":1}
        gid = int(t_group.objects.get(is_delete=0,group_name=data["gname"]).id)
        if int(data["type"]) == 0:
            t_address.objects.create(address=data["address"],groupid=gid)
            address_sel_value, address_sel = other_address_sel(gid)
            # user_sel_value, user_sel = other_user_sel(gid)
            return_json = {
                "address_sel_value": address_sel_value,
                "address_sel": address_sel,
                "status": 0
            }
        elif int(data["type"]) == 1:
            ist_data = data["data"]
            ist_data["groupid"] = gid
            t_user.objects.create(**ist_data)
            user_sel_value, user_sel = other_user_sel(gid)
            return_json = {
                "user_sel_value": user_sel_value,
                "user_sel": user_sel,
                "status": 0
            }
        elif int(data["type"]) == 2:
            dataO = eval(data["data"])

            if data["opt_type"] == "add":
                params = dataO["params_list"]
                del dataO["params_list"]
                dataO["c_id"] = data["c_id"]
                olist = list(t_interface.objects.filter(url=dataO["url"],c_id=dataO["c_id"]))
                if len(olist) == 0:
                    t_interface.objects.create(**dataO)
                    oid = int(t_interface.objects.get(url=dataO["url"], c_id=dataO["c_id"]).id)
                    print(oid)
                    for item in params:
                        item["i_id"] = oid
                        t_interface_params.objects.create(**item)
                    itf_list = itf_list_sel(data["gname"])
                    return_json = {
                        "itf_list": itf_list,
                        "status": 0
                    }
                else:
                    return_json = {"status": 2}
            elif data["opt_type"] == "mod":
                t_id = int(data["mod_id"])
                url_json, url_table = interface_sel(t_id)
                new_url_table = dataO["params_list"]
                dataO["params_list"] = []
                del_list = [i for i in url_table if i not in new_url_table]
                add_list = [i for i in new_url_table if i not in url_table]
                mod_json = {}
                for k,v in dataO.items():
                    if v != url_json[k]:
                        mod_json[k] = v
                if mod_json != {}:
                    t_interface.objects.filter(id=t_id).update(**mod_json)
                for a in del_list:
                    t_interface_params.objects.filter(i_id=t_id, param_name=a["param_name"]).update(delete=1)
                for b in add_list:
                    b["i_id"] = t_id
                    t_interface_params.objects.create(**b)

                
                itf_list = itf_list_sel(data["gname"])
                return_json = {
                    "itf_list": itf_list,
                    "status": 0
                }
        elif int(data["type"]) == 3:
            ist_data = data["data"]
            ist_data["g_id"] = gid
            t_total.objects.create(**ist_data)
            itf_list = itf_list_sel(data["gname"])
            return_json = {
                "itf_list":itf_list,
                "status": 0
            }
        return HttpResponse(json.dumps(return_json))

@csrf_exempt
def itf_otherdel(request):
    pass


def other_address_sel(gid):
    a_data = t_address.objects.filter(groupid=gid,is_delete=0).values_list("addressid","address")
    key_list = ["value", "label"]
    a_list  = []
    a_totle = ""
    for a_item in a_data:
        a_json = {}
        for u_num in range(len(key_list)):
            a_json[key_list[u_num]] = a_item[u_num]
        a_list.append(a_json)
    if len(a_list) > 0:
        a_totle = a_list[0]["value"]

    return a_totle, a_list

def other_user_sel(gid):
    u_data = t_user.objects.filter(groupid=gid,is_delete=0).values_list("userid","username")
    key_list = ["value", "label"]
    u_list  = []
    u_totle = ""
    for u_item in u_data:
        u_json = {}
        for u_num in range(len(key_list)):
            u_json[key_list[u_num]] = u_item[u_num]
        u_list.append(u_json)
    if len(u_list) > 0:
        u_totle = u_list[0]["value"]
    return u_totle, u_list



@csrf_exempt
def itf_groupops(request):
    if request.method == "POST":
        _status = 1
        try:
            data = eval(request.body)
            if data["type"] == 0:
                t_group.objects.create(group_name=data["gname"])
            elif data["type"] == 1:
                t_group.objects.filter(group_name=data["gname"]).update(is_delete=1)
            _status = 0
        except BaseException as b:
            _log_err = "itf_groupops函数报错 --》" + str(b)
            print(_log_err)
        finally:
            group_data = t_group.objects.filter(is_delete=0).values_list('group_name')
            group_list = []
            for i in group_data:
                group_list.append(i[0])
            return HttpResponse(json.dumps({"status":_status,"group_list":group_list}))

